package com.appinfo.service;

import com.appinfo.annotation.AvoidRepeatableCommit;
import com.appinfo.mapper.AppMapper;
import com.appinfo.pojo.AppInfo;
import com.appinfo.pojo.AppVersion;
import com.appinfo.pojo.DevUser;
import com.appinfo.utils.CheckObjectIsNull;
import com.appinfo.vo.AppInfoVo;
import com.appinfo.vo.AppVersionVo;
import com.appinfo.vo.Pages;
import com.appinfo.vo.QueryVo;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AppServiceImpl implements AppService{
    //平台码
    private static final String FLATFORMCODE = "APP_FLATFORM";
    //app状态码
    private static final String STATUSCODE = "APP_STATUS";

    @Autowired
    private AppMapper appMapper;

    @Autowired
    private AppVersionService appVersionService;


    /**
     * 分页查询appinfo
     * @param pages
     * @return
     */
    @Override
    public Pages<AppInfoVo> queryAppInfoPage(Pages pages,QueryVo queryVo) {
        //Pages<AppInfoVo> pages = new Pages<>();
        pages.setSize(5);
        //查询分页
        List<AppInfo> appInfos = null;
        if (pages != null || !CheckObjectIsNull.objCheckIsNull(pages)) {

            pages.setStartRow((pages.getPageIndex()-1) * pages.getSize());

            appInfos = appMapper.selectAppInfoByQueryVo(pages);

            pages.setTotalCount(appMapper.countAppListByQueryVo(pages));
            if (pages.getTotalCount() % pages.getSize() != 0) {
                pages.setTotalPageCount((pages.getTotalCount() / pages.getSize()) + 1);
            } else {
                pages.setTotalPageCount((pages.getTotalCount() / pages.getSize()));
            }
            pages.setCurrentPageNo(pages.getPageIndex());


        }

        //转换
        List<AppInfoVo> appInfoVos = appInfos.stream().map(appInfo -> {
            AppInfoVo appInfoVo = new AppInfoVo();
            BeanUtils.copyProperties(appInfo, appInfoVo);  //拷贝属性
            //分类名称
            String categoryLevel1Name = queryCategoryLevelNamesById(appInfo.getCategoryLevel1());
            String categoryLevel2Name = queryCategoryLevelNamesById(appInfo.getCategoryLevel2());
            String categoryLevel3Name = queryCategoryLevelNamesById(appInfo.getCategoryLevel3());
            //状态名称
            String statusName = queryTypeNameByFId(appInfo.getStatus(),STATUSCODE);
            //平台名称
            String flatformName = queryTypeNameByFId(appInfo.getFlatformId(),FLATFORMCODE);
            //版本号
            String versionNo = queryVersionNoByVId(appInfo.getId());

            appInfoVo.setCategoryLevel1Name(categoryLevel1Name);
            appInfoVo.setCategoryLevel2Name(categoryLevel2Name);
            appInfoVo.setCategoryLevel3Name(categoryLevel3Name);
            appInfoVo.setFlatformName(flatformName);
            appInfoVo.setStatusName(statusName);
            appInfoVo.setVersionNo(versionNo);
            return appInfoVo;

        }).collect(Collectors.toList());

        pages.setRows(appInfoVos);
        return pages;
    }

    @Override
    public AppInfo queryAPKNameByName(String apkName) {

        if(StringUtils.isEmpty(apkName)){
            AppInfo appInfo = new AppInfo();
            appInfo.setAPKName("empty");
            return appInfo;
        }
        AppInfo appInfo = appMapper.queryAPKNameByName(apkName);
        if(appInfo == null || CheckObjectIsNull.objCheckIsNull(appInfo)){
            appInfo = new AppInfo();
            appInfo.setAPKName("noexist");
            return appInfo;
        }else {
            appInfo.setAPKName("exist");
            return appInfo;
        }
    }

    @Override
    @Transactional
    public void saveApp(AppInfo appInfo, DevUser devUser) {
        //补全属性
        Long devUserId = devUser.getId();
        //    private Long versionId;//` bigint(30) DEFAULT NULL COMMENT '最新的版本id',
        appInfo.setDevId(devUserId);
        appInfo.setUpdateDate(new Date());
        appInfo.setCreatedBy(devUserId);
        appInfo.setCreationDate(new Date());
        appInfo.setModifyBy(devUserId);
        appInfo.setModifyDate(new Date());


        appMapper.saveApp(appInfo);
    }

    @Override
    public AppInfoVo queryAppInfoById(Long id) {
        AppInfo appInfo = appMapper.queryAppInfoById(id);
        AppInfoVo appInfoVo = new AppInfoVo();
        if(appInfo == null || CheckObjectIsNull.objCheckIsNull(appInfo)){
            return null;
        }
        BeanUtils.copyProperties(appInfo,appInfoVo);
        //补全属性
        appInfoVo.setStatusName(queryTypeNameByFId(appInfoVo.getStatus(),STATUSCODE));
        // private String versionNo; //版本号
        appInfoVo.setVersionNo(queryVersionNoByVId(appInfoVo.getVersionId()));
        return appInfoVo;
    }

    @Override
    @Transactional
    public void updateAppInfoByVo(AppInfoVo appInfoVo,DevUser devUser) {
        appInfoVo.setModifyDate(new Date());
        appInfoVo.setModifyBy(devUser.getId());
        appMapper.updateAppInfoByVo(appInfoVo);

    }

    @Override
    public String querySoftwareNameById(Long id) {
        AppInfo appInfo = appMapper.queryAppInfoById(id);
        return appInfo.getSoftwareName();
    }

    @Override
    public void updateAppInfoVersionById(Long vid,Long appId) {
        appMapper.updateAppInfoVersionById(vid,appId);
    }

    /**
     * 查询app信息
     * @param appInfoId
     * @return
     */
    @Override
    public AppInfoVo checkAppInfoById(long appInfoId) {
        AppInfo appInfo = appMapper.checkAppInfoById(appInfoId);

        AppInfoVo appInfoVo = new AppInfoVo();

        //分类名称
        String categoryLevel1Name = queryCategoryLevelNamesById(appInfo.getCategoryLevel1());
        String categoryLevel2Name = queryCategoryLevelNamesById(appInfo.getCategoryLevel2());
        String categoryLevel3Name = queryCategoryLevelNamesById(appInfo.getCategoryLevel3());
        //状态名称
        String statusName = queryTypeNameByFId(appInfo.getStatus(),STATUSCODE);
        //平台名称
        String flatformName = queryTypeNameByFId(appInfo.getFlatformId(),FLATFORMCODE);
        //版本号
        String versionNo = queryVersionNoByVId(appInfo.getId());

        appInfoVo.setCategoryLevel1Name(categoryLevel1Name);
        appInfoVo.setCategoryLevel2Name(categoryLevel2Name);
        appInfoVo.setCategoryLevel3Name(categoryLevel3Name);
        appInfoVo.setFlatformName(flatformName);
        appInfoVo.setStatusName(statusName);
        appInfoVo.setVersionNo(versionNo);

        //转换
        BeanUtils.copyProperties(appInfo,appInfoVo );

        return appInfoVo;

    }



    /**
     * 查询版本信息
     * @param appInfoId
     * @return
     */
    @Override
    public List<AppVersionVo> checkVersionInfoById(long appInfoId) {

        List<AppVersion> appVersions = appMapper.checkVersionInfoById(appInfoId);

        List<AppVersionVo> appVersionVos = appVersions.stream().map(appVersion -> {

            AppVersionVo appVersionVo = new AppVersionVo();
            //拷贝属性
            BeanUtils.copyProperties(appVersion, appVersionVo);

            String publishStatusName = querypublishStatusNameByStatus(appVersion.getPublishStatus(), "PUBLISH_STATUS");
            String appName = queryappNameById(appVersion.getAppId());

            appVersionVo.setAppName(appName);
            appVersionVo.setPublishStatusName(publishStatusName);

            return appVersionVo;

        }).collect(Collectors.toList());

        return appVersionVos;

    }


    /**
     * 删除APP
     * @param appInfoId
     */
    @Override
    public void delAppInfoById(Long appInfoId) {
        appMapper.delAppInfoById(appInfoId);
    }


    /**
     * 商品上下架
     * @param appid
     */
    @Override
    public boolean updateSaleStatusByAppId(Long appid) {

        AppInfo appInfo = appMapper.checkAppInfoById(appid);

        int isUpdateSuccess = 0;

        //上架
        if (appInfo.getStatus() == 2 || appInfo.getStatus() == 5) {
            isUpdateSuccess = appMapper.onSale(appid);
            if (isUpdateSuccess!=0) {
                return true;
            }
        } else if (appInfo.getStatus() == 4) {
            //下架
            isUpdateSuccess = appMapper.offSale(appid);
            if (isUpdateSuccess!=0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean DelFile(Long id, String flag) {
        try {
            AppInfo appInfo = appMapper.queryAppInfoById(id);
            if (flag.equals("logo")) {
                File file = new File(appInfo.getLogoLocPath());
                if(file.isFile() && file.exists()){
                    file.delete();
                }
                appMapper.delAppInfoLogo(id);
            }else if (flag.equals("apk")){
                File file = new File(appInfo.getLogoLocPath());
                if(file.isFile() && file.exists()){
                    file.delete();
                }
                appVersionService.delAppApkById(id);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 查询最新版本号
     * @param appId
     * @return
     */
    private String queryVersionNoByVId(Long appId) {
        String versionNo = appMapper.queryVersionNoByVId(appId);
        return versionNo;
    }

    /**
     * 查询类别--状态名
     * @param valueId
     * @param typeCode
     * @return
     */
    private String queryTypeNameByFId(Long valueId, String typeCode) {
        String typeName = appMapper.queryTypeNameByFId(valueId,typeCode);
        return typeName;
    }



    private String queryCategoryLevelNamesById(Long levelId) {
        String levelName = appMapper.queryCategoryLevelNamesById(levelId);
        return levelName;
    }


    private String querypublishStatusNameByStatus(Long publicStatus, String typeCode) {
        String publishStatusName = appMapper.querypublishStatusNameByStatus(publicStatus,typeCode);
        return publishStatusName;
    }

    private String queryappNameById(Long appId) {
        String appName = appMapper.queryappNameById(appId);
        return appName;
    }
}
